#!/bin/bash

# input
read -p "Please enter the user name to config Java env (default: root):" USERNAME

if [ -z "$USERNAME" ]; then
    USERNAME=$HOME
else
    USERNAME=/home/$USERNAME
fi

check_command() {
    command -v "$1" >/dev/null
    if [ $? -ne 0 ]; then
        echo "Command not found, please install $1 command and try again."
        exit 1
    fi
}

get_os_type() {
    if [ "$(uname)" == "Darwin" ]; then
        os="darwin"
    elif [ "$(uname)" == "Linux" ]; then
        os="linux"
    else
        echo "Failed to get system type."
        exit 1
    fi
}

get_arch() {
    if [ $(arch) == "x86_64" ]; then
        arch="x64"
    elif [ $(arch) =~ "aarch64" ]; then
        arch="arm64"
    else
        echo "Failed to get system arch."
        exit 1
    fi
}

install_java8() {
    wget https://repo.huaweicloud.com/java/jdk/8u202-b08/jdk-8u202-linux-x64.tar.gz

    tar -zxvf jdk-8u202-linux-x64.tar.gz -C /usr/local/

    rm -rf /usr/local/java

    mv /usr/local/jdk1.8.0_202 /usr/local/java

    rm -rf jdk-8u202-linux-x64.tar.gz

    chown -R root /usr/local/java

    chgrp -R root /usr/local/java

    echo "export JAVA_HOME=/usr/local/java" >>$USERNAME/.bashrc
    echo -e "export PATH=\$PATH:\$JAVA_HOME/bin" >>$USERNAME/.bashrc

    source $USERNAME/.bashrc

    java -version
}

main() {
    check_command "wget"
    get_os_type
    get_arch
    install_java8
}

main
